package container

import (
	"context"
	"fmt"
	"github.com/Unixeno/islands/cmd/connection"
	"github.com/Unixeno/islands/cmd/utils"
	"github.com/Unixeno/islands/pb"
	"github.com/spf13/cobra"
)

var waitCondition string

func GetContainerWaitCmd() *cobra.Command {

	containerWaitCmd := &cobra.Command{
		Use:   "wait id",
		Short: "Block until one container stop, then print its exit codes",
		Args:  cobra.MinimumNArgs(1),
		Run:   containerWaitHandle,
	}
	containerWaitCmd.Flags().StringVarP(&waitCondition, "condition", "c", "not-running", "set condition for container waiting")
	return containerWaitCmd
}

func containerWaitHandle(cmd *cobra.Command, args []string) {
	id := CheckNameOrId(args[0])
	r, err := connection.Client.WaitContainer(context.Background(), &pb.WaitContainerReq{
		Id:        id,
		Condition: waitCondition,
	})
	if err != nil {
		fmt.Printf("Cannot wait container to stop for reason %v\n", err)
	} else {
		if !utils.PrintError(r.Err) {
			fmt.Println(r.ExitCode)
		}
	}
}
